package cn.ijero.composeui.page.advanced.custom

import android.content.Context
import android.content.Intent
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import cn.ijero.composeui.base.BaseActivity
import cn.ijero.composeui.tool.HorizontalSpacer
import cn.ijero.composeui.tool.VerticalSpacer

class CanvasActivity : BaseActivity() {

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, CanvasActivity::class.java)
            context.startActivity(starter)
        }
    }

    @Composable
    override fun RenderContent() {
        RootLayout()
    }
}

@Composable
private fun RootLayout() {
    var progress by remember {
        mutableStateOf(50)
    }
    Column(modifier = Modifier.fillMaxSize()) {
        VerticalSpacer()
        VerticalSpacer()
        CircleProgress(progress = progress, modifier = Modifier.align(Alignment.CenterHorizontally))
        VerticalSpacer()
        Row(modifier = Modifier.align(Alignment.CenterHorizontally)) {
            Button(onClick = {
                if (progress > 0) {
                    progress -= 10
                }
            }) {
                Text(text = "进度-10")
            }
            HorizontalSpacer()
            Button(onClick = {
                if (progress < 100) {
                    progress += 10
                }
            }) {
                Text(text = "进度+10")
            }
        }
    }
}

@Composable
private fun CircleProgress(progress: Int, modifier: Modifier) {
    val animatable = remember { Animatable(0f) }
    LaunchedEffect(key1 = progress, block = { animatable.animateTo(progress * 360f / 100) })
    val sweepAngle by animateFloatAsState(targetValue = animatable.value, animationSpec = tween(60))
    Box(modifier = modifier) {
        Text(text = "$progress%", modifier = Modifier.align(Alignment.Center))
        Canvas(modifier = Modifier.size(160.dp)) {
            drawArc(
                color = Color.Red,
                startAngle = -90f,
                sweepAngle = sweepAngle,
                useCenter = false,
                style = Stroke(width = 4.dp.toPx(), cap = StrokeCap.Round)
            )
        }
    }
}

@Preview
@Composable
private fun DefaultPreview() {
    RootLayout()
}